/**
 * Created with JetBrains WebStorm.
 * User: mumble
 * Date: 6/24/12
 * Time: 10:09 AM
 * To change this template use File | Settings | File Templates.
 */
var WebSocketServer = require('ws').Server,
    config = require('../configuration/configuration').Configuration,
    GameManager = require('../modules/GameManager').GameManager,
    Defines = require('../command/Defines').Defines;


function Client(server,  clientId, conn)
{
    this.server = server;
    this.clientId = clientId;
    this.conn = conn;
    this.last_ping = 0;
}

function LobbyServer(service, options)
{
    this.service = service;
    this.host = options.host || config.host;
    this.port = options.port || config.websocket_port;
    this.max_connection = options.max_connection || config.max_connection;
    this.wsServer = null;
    this.connection_count = 0;
    this.client_id = 0;
    this.clients = {};
    this.min_absent_id = 0;

    this.gameManager  = new GameManager(service);
}

LobbyServer.prototype = {
    init : function(cb)
    {
        var err;
        this.gameManager.init(err,cb);


    },
    startServer : function()
    {
        console.log('lobby server is staring...');
        var that = this;
        this.wsServer = new WebSocketServer({
            host: this.host,
            port : this.port
        });

        this.wsServer.on('connection', function(conn){
            if(that.connection_count > that.max_connection)
            {
                console.log('Server is busy now!');
                conn.close();
                return;
            }

            ++that.connection_count;

            var i = that.min_absent_id;
            while(that.clients[i] && i <= that.client_id) ++i;

            if(i == that.client_id)
            {
                ++that.client_id;
            }


            var client = new Client(that, i, conn);
            that.clients[i] = client;
            client.last_ping = that.getCurrentTime();
            conn.client = client;

            console.log("Co ket noi moi, clientId = "+client.clientId);

            conn.on('message', function(data, flags) {
                console.log('Nhan ban tin tu client '+ this.client.clientId);
                var package = null;
                try
                {
                    package = JSON.parse(data);
                } catch (e)
                {
                    console.log('Invalid message');
                    return;
                }

                switch (package[0])
                {
                    case Defines.PING_PACKAGE :
                        self.processPingPackage(package[1]);
                        break;
                    case Defines.GAME_PACKAGE:
                        self.processGamePackage(package[1]);
                        break;
                    default :
                        self.procesControlPackage(package[1]);

                }
            });
            conn.on('close', function(){
                if(this.client)
                {
                    var clientId = this.client.clientId;
                    console.log('Client ' + clientId +' is disconnected');
                    delete that.clients[clientId];

                    if(that.min_absent_id > clientId)
                    {
                        that.min_absent_id = clientId;
                    }


                }
                --that.connection_count;

            });
            conn.on('error', function(e){
                if(this.client)
                {
                    var clientId = this.client.clientId;
                    delete that.clients[clientId];

                    if(that.min_absent_id > clientId)
                    {
                        that.min_absent_id = clientId;
                    }


                }
                --that.connection_count;
            });



        });
    },
    getCurrentTime : function()
    {
        return new Date().getTime();

    },
    processPingPackage : function(package)
    {

    },
    processGamePackage : function(package)
    {

    },
    processControlPackage : function(package)
    {

    },
    sendMessage : function(clientId, package)
    {
        var client = this.clients[clientId];
        if(client)
            client.send(JSON.stringify(package));
    }



};

module.exports.LobbyServer = LobbyServer;